package com.ktgj.customer.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ktgj.common.log.annotation.SignatureValidation;
import com.ktgj.customer.domain.Customer;
import com.ktgj.customer.domain.PointRecord;
import com.ktgj.customer.domain.vo.CustomerIdVo;
import com.ktgj.customer.domain.vo.IntegralVo;
import com.ktgj.customer.domain.vo.PointRecordListVo;
import com.ktgj.customer.service.ICustomerService;
import com.ktgj.customer.service.ILoginService;
import com.ktgj.customer.service.IPointRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ktgj.common.log.annotation.Log;
import com.ktgj.common.log.enums.BusinessType;
import com.ktgj.common.security.annotation.PreAuthorize;
import com.ktgj.common.core.web.controller.BaseController;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.common.core.utils.poi.ExcelUtil;
import com.ktgj.common.core.web.page.TableDataInfo;

/**
 * 积分明细
Controller
 * 
 * @author ruoyi
 * @date 2021-07-27
 */
@ControllerAdvice
@RestController
@RequestMapping("/record")
public class PointRecordController extends BaseController
{
    @Autowired
    private IPointRecordService pointRecordService;
    @Autowired
    private ILoginService loginService;
    @Autowired
    private ICustomerService customerService;

    /**
     * 查询积分明细
列表
     */
    //@PreAuthorize(hasPermi = "system:record:list")
    @GetMapping("/list")
    public TableDataInfo list(PointRecord pointRecord)
    {
        startPage();
        List<PointRecord> list = pointRecordService.selectPointRecordList(pointRecord);
        return getDataTable(list);
    }

    /**
     * 导出积分明细
列表
     */
    //@PreAuthorize(hasPermi = "system:record:export")
    //@Log(title = "积分明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PointRecord pointRecord) throws IOException
    {
        List<PointRecord> list = pointRecordService.selectPointRecordList(pointRecord);
        ExcelUtil<PointRecord> util = new ExcelUtil<PointRecord>(PointRecord.class);
        util.exportExcel(response, list, "积分明细数据");
    }

    /**
     * 获取积分明细
详细信息
     */
    //@PreAuthorize(hasPermi = "system:record:query")
    @GetMapping(value = "/{pntRecordId}")
    public AjaxResult getInfo(@PathVariable("pntRecordId") Long pntRecordId)
    {
        return AjaxResult.success(pointRecordService.selectPointRecordById(pntRecordId));
    }

    /**
     * 新增积分明细

     */
    //@PreAuthorize(hasPermi = "system:record:add")
    //@Log(title = "积分明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PointRecord pointRecord)
    {
        return toAjax(pointRecordService.insertPointRecord(pointRecord));
    }

    /**
     * 修改积分明细

     */
    //@PreAuthorize(hasPermi = "system:record:edit")
    //@Log(title = "积分明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PointRecord pointRecord)
    {
        return toAjax(pointRecordService.updatePointRecord(pointRecord));
    }

    /**
     * 删除积分明细

     */
    //@PreAuthorize(hasPermi = "system:record:remove")
    //@Log(title = "积分明细", businessType = BusinessType.DELETE)
	@DeleteMapping("/{pntRecordIds}")
    public AjaxResult remove(@PathVariable Long[] pntRecordIds)
    {
        return toAjax(pointRecordService.deletePointRecordByIds(pntRecordIds));
    }


    /**
     * 查询当前用户的积分
     */
//    @SignatureValidation
    @PostMapping("/selectAvailableIntegral")
    public AjaxResult selectAvailableIntegral(HttpServletRequest request) {
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        IntegralVo integralVo;
        try {
            integralVo = pointRecordService.queryUserCredits(customer.getCustomerId());
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(integralVo);
    }


    /**
     * 查看用户可用积分
     */
    @PostMapping("/queryUserCreditsNum")
    public AjaxResult queryUserCreditsNum(HttpServletRequest request) {
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        Long aLong;
        try {
            aLong = pointRecordService.queryUserCreditsNum(customer.getCustomerId());
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(aLong);
    }

    /**
     * 查看用户可用积分
     */
    @PostMapping("/queyUserCreditsNumByToken")
    public AjaxResult queyUserCreditsNumByToken(@RequestParam("token")String token) {
        Customer customer;
        try {
            customer = loginService.getLoginCustomerByToken(token);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        Long aLong;
        try {
            aLong = pointRecordService.queryUserCreditsNum(customer.getCustomerId());
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(aLong);
    }

    /**
     * 查看用户可用积分（CRM）
     */
    @PostMapping("/queyUserCreditsNumByCustomerId")
    public AjaxResult queyUserCreditsNumByCustomerId(@RequestParam("customerId") Long customerId) {
        Long aLong = null;
        try {
            aLong = pointRecordService.queryUserCreditsNum(customerId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(aLong);
    }


    /**
     * 用户签到领取积分
     */
    @PostMapping("/signIn")
    public AjaxResult signIn(HttpServletRequest request) {
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        return toAjax(pointRecordService.signIn(customer.getCustomerId()));
    }

    /**
     *
     * 花费积分
     *
     * @param customerId 会员id
     * @param creditsNum 要扣减的积分
     * @param orderType 订单类型
     * @param orderId 订单id
     * @param orderSourceDesc 订单描述（客户端展示使用），例如机票 显示航程+航班号
     * @param couponId 使用优惠卷的id
     * @return
     */
    @PostMapping("/spend")
    public AjaxResult spend(@RequestParam("customerId") Long customerId, @RequestParam("creditsNum") Long creditsNum, @RequestParam("orderType") String orderType,
                            @RequestParam("orderId") Long orderId, @RequestParam("orderSourceDesc") String orderSourceDesc, @RequestParam("couponId") Long couponId,
                            @RequestParam("usedDeposit") BigDecimal usedDeposit, @RequestParam("employeeId") Long employeeId) {
        String spend;
        try {
            spend = pointRecordService.spend(customerId, creditsNum, orderType, orderId, orderSourceDesc, couponId, employeeId);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.success(spend);
    }

    /**
     * 积分记录列表
     * */
    @PostMapping("/pointRecordList")
    public TableDataInfo pointRecordList(@RequestBody PointRecordListVo pointRecordListVo){
        startPage();
        List<PointRecord> pointRecordList;
        try {
            pointRecordList = pointRecordService.pointRecordList(pointRecordListVo);
        } catch (Exception e){
            List<PointRecord> pointRecords = new ArrayList<>();
            PointRecord pointRecord = new PointRecord();
            pointRecord.setMsg(e.getMessage());
            pointRecords.add(pointRecord);
            return getDataTable(pointRecords);
        }

        return getDataTable(pointRecordList);
    }

    /**
     * 会员积分调整
     * */
    @PostMapping("/adjustment")
    public AjaxResult adjustment(HttpServletRequest request, @RequestBody PointRecord pointRecord){
        int i;
        try {
            i = pointRecordService.adjustment(pointRecord, request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (i > 0){
            return AjaxResult.success("调整成功");
        }
        else {
            return AjaxResult.error("调整失败");
        }
    }

    /**
     * 会员积分列表（姓名，卡号，积分）
     * */
    @PostMapping("/information")
    public AjaxResult information(@RequestBody Map<String, Object> map){
        Long id = 0l;
        String name = null;
        String cardNum = null;
        String phone = null;
        if (map.get("id") != null && !map.get("id").equals("")){
            id = Long.valueOf(map.get("id").toString());
        }
        if (map.get("name") != null && !map.get("name").equals("")){
            name = map.get("name").toString();
        }
        if (map.get("cardNum") != null && !map.get("cardNum").equals("")){
            cardNum = map.get("cardNum").toString();
        }
        if (map.get("phone") != null && !map.get("phone").equals("")){
            phone = map.get("phone").toString();
        }

        if (id == 0 && name == null && cardNum == null && phone == null){
            return AjaxResult.error("至少需要填一个参数");
        }

        CustomerIdVo customerIdVo = new CustomerIdVo();
        if (id != 0){
            customerIdVo.setCustomerId(id);
        }
        if (name != null){
            customerIdVo.setCustomerName(name);
        }
        if (cardNum != null){
            customerIdVo.setCustomerCard(cardNum);
        }
        if (phone != null){
            customerIdVo.setCustomerPhone(phone);
        }
        try {
            customerIdVo = customerService.customerId(customerIdVo);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.success(customerIdVo);
    }

    /**
     * 积分审核
     * */
    @PostMapping("/pointReview")
    public AjaxResult pointReview(HttpServletRequest request, @RequestBody Map<String, Object> map){
        Long id = Long.valueOf(map.get("id").toString());
        int i;
        try {
            i = pointRecordService.pointReview(request, id);
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }

        if (i > 0){
            return AjaxResult.success("审核成功");
        }
        else {
            return AjaxResult.error("审核失败");
        }
    }

    /**
     * 当前会员可支配积分
     * */
    @PostMapping("/dominateIntegral")
    public Long dominateIntegral(@RequestBody Map<String, Object> map){
        Long id = Long.valueOf(map.get("id").toString());
        Long integral = pointRecordService.dominateIntegral(id);
        return integral;
    }

    /**
     * 当前会员可支配积分
     * */
    @PostMapping("/BackDominateIntegral")
    public Long BackDominateIntegral(HttpServletRequest request){
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);
        } catch (Exception e){
            return 0l;
        }

        Long integral;
        if (customer != null){
            integral = pointRecordService.dominateIntegral(customer.getCustomerId());
        }
        else {
            integral = 0l;
        }

        return integral;
    }
}
